import 'dart:convert';

class JsonUtil {
  static String? encodeObj(dynamic value) {
    return value != null ? jsonEncode(value) : null;
  }

  static T? getObject<T>(dynamic source, T f(Map v)) {
    if (source == null || source.toString().isEmpty) return null;
    try {
      Map map;
      if (source is String) {
        if (source.isNotEmpty) {
          map = json.decode(source) as Map<dynamic, dynamic>;
        } else {
          map = {};
        }
      } else {
        map = source as Map<dynamic, dynamic>;
      }
      return f(map);
    } catch (e) {
      print('JsonUtil convert error, Exception：${e.toString()}');
    }
    return null;
  }

  static List<T>? getObjectList<T>(dynamic source, T f(Map v)) {
    if (source == null || source.toString().isEmpty) return null;
    try {
      List list;
      if (source is String) {
        if (source.isNotEmpty) {
          list = json.decode(source) as List<dynamic>;
        } else {
          list = [];
        }
      } else {
        list = source as List<dynamic>;
      }
      return list.map((dynamic value) {
        if (value is String) {
          if (value.isNotEmpty) {
            value = json.decode(value) as Map<dynamic, dynamic>;
          } else {
            value = {};
          }
          // value = json.decode(value);
        }
        return f(value as Map<dynamic, dynamic>);
      }).toList();
    } catch (e) {
      print('JsonUtil convert error, Exception：${e.toString()}');
    }
    return null;
  }
}
